package com.merelyb.task.handle.dictarea;

import com.merelyb.data.service.service.mybatis.bean.dict.DictArea;
import com.merelyb.data.service.service.service.dict.DictAreaService;
import com.merelyb.util.HttpClientUtil;
import com.merelyb.util.JsonUtils;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LiM on 2017/11/15.
 * 获取行政区域
 * 获取地址 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/
 */
@Service
public class DictAreaGetHandler {
    @Autowired
    DictAreaService dictAreaService;

    private String sReplace = ".html";
    private String sHref = "href";
    private String sHomeUrl = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/";

    /**
     * 主页面获取
     */
    public void getDictArea() {
        List<DictArea> dictAreaList = new ArrayList<>();
        getProvince(sHomeUrl + "index.html", 0L, "0");
    }

    /**
     * 截取字符串
     *
     * @param sCode
     * @return
     */
    private String getCode(String sCode) {
        return sCode.substring(sCode.lastIndexOf("/") + 1, sCode.length());
    }

    /**
     * 获取链接
     *
     * @param sUrl
     * @return
     */
    private String getUrl(String sUrl) {
        return sUrl.substring(0, sUrl.lastIndexOf("/") + 1);
    }

    private String getString(String sData) {
        if (sData.equals("")) return "";
        String sReturn = "";
        JSONObject jsonObject = new JSONObject(sData);
        if (jsonObject.has("map")) {
            jsonObject = jsonObject.getJSONObject("map");
        }
        if (jsonObject.has("data")) {
            sReturn = jsonObject.getString("data");
        }else {
            sReturn = "";
        }
        return sReturn;
    }

    /**
     * 省份页面解析
     *
     * @param sUrl
     * @param iParent
     * @param sParents
     */
    private void getProvince(String sUrl, long iParent, String sParents) {
        List<String> urlList = new ArrayList<>();
        String sResult = getString(HttpClientUtil.httpGetRequest(sUrl, "GB2312"));
        if (sResult.equals("")) return;
        Document document = Jsoup.parse(sResult);
        Elements elements = document.getElementsByAttributeValue("class", "provincetable");
        if (elements != null && elements.size() > 0) {
            Element eleTable = elements.get(0);
            Elements eleTRs = eleTable.child(0).children().toggleClass("provincetr");
            if (eleTRs != null && eleTRs.size() > 0) {
                for (int i = 3; i < eleTRs.size(); i++) {
                    Element eleTR = eleTRs.get(i);
                    for (Element eleA : eleTR.getElementsByTag("a")
                            ) {
                        List<DictArea> dictAreaList = new ArrayList<>();
                        DictArea dictArea = new DictArea();
                        dictArea.setAreaName(eleA.text());
                        dictArea.setId(Long.parseLong(eleA.attr(sHref).replace(sReplace, "")));
                        dictArea.setAreaType(0);
                        dictArea.setIsDelete(0);
                        dictArea.setCreateTime(new Date());
                        dictArea.setParentId(iParent);
                        dictArea.setParentsIds(sParents);
                        dictArea.setAreaCode("");
                        dictAreaList.add(dictArea);
                        try {
                            dictAreaService.addData(dictAreaList);
                            dictAreaList.clear();
                            getCity(getUrl(sUrl) + eleA.attr(sHref), Long.parseLong(eleA.attr(sHref).replace(sReplace, "")),
                                    sParents + "," + eleA.attr(sHref).replace(sReplace, ""), dictAreaList);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }
    }

    /**
     * 市页面解析
     *
     * @param sUrl
     * @param iParent
     * @param sParents
     * @param dictAreaList
     */
    private void getCity(String sUrl, long iParent, String sParents, List<DictArea> dictAreaList) {
        String sResult = getString(HttpClientUtil.httpGetRequest(sUrl, "GB2312"));
        if (sResult.equals("")) return;
        Document document = Jsoup.parse(sResult);
        Elements elements = document.getElementsByAttributeValue("class", "citytable");
        if (elements != null && elements.size() > 0) {
            Element eleTable = elements.get(0);
            Elements eleTRs = eleTable.child(0).children().toggleClass("citytr");
            if (eleTRs != null && eleTRs.size() > 0) {
                for (Element eleTR : eleTRs
                        ) {
                    Elements eleAs = eleTR.getElementsByTag("a");
                    if (eleAs != null && eleAs.size() > 0) {
                        DictArea dictArea = new DictArea();
                        dictArea.setAreaName(eleAs.get(1).text());
                        dictArea.setId(Long.parseLong(getCode(eleAs.get(0).attr(sHref).replace(sReplace, ""))));
                        dictArea.setAreaType(1);
                        dictArea.setIsDelete(0);
                        dictArea.setCreateTime(new Date());
                        dictArea.setParentId(iParent);
                        dictArea.setParentsIds(sParents);
                        dictArea.setAreaCode(eleAs.get(0).text());
                        dictAreaList.add(dictArea);
                        try {
                            dictAreaService.addData(dictAreaList);
                            dictAreaList.clear();
                            getCounty(getUrl(sUrl) + eleAs.get(0).attr(sHref), Long.parseLong(getCode(eleAs.get(0).attr(sHref).replace(sReplace, ""))),
                                    sParents + "," + getCode(eleAs.get(0).attr(sHref).replace(sReplace, "")), dictAreaList);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
    }

    /**
     * 区域页面解析
     *
     * @param sUrl
     * @param iParent
     * @param sParents
     * @param dictAreaList
     */
    private void getCounty(String sUrl, long iParent, String sParents, List<DictArea> dictAreaList) {
        String sResult = getString(HttpClientUtil.httpGetRequest(sUrl, "GB2312"));
        if (sResult.equals("")) return;
        Document document = Jsoup.parse(sResult);
        Elements elements = document.getElementsByAttributeValue("class", "countytable");
        if (elements != null && elements.size() > 0) {
            Element eleTable = elements.get(0);
            Elements eleTRs = eleTable.child(0).children().toggleClass("countytr");
            if (eleTRs != null && eleTRs.size() > 0) {
                for (Element eleTR : eleTRs
                        ) {
                    Elements eleAs = eleTR.getElementsByTag("a");
                    if (eleAs != null && eleAs.size() > 0) {
                        DictArea dictArea = new DictArea();
                        dictArea.setAreaName(eleAs.get(1).text());
                        dictArea.setId(Long.parseLong(getCode(eleAs.get(0).attr(sHref).replace(sReplace, ""))));
                        dictArea.setAreaType(2);
                        dictArea.setIsDelete(0);
                        dictArea.setCreateTime(new Date());
                        dictArea.setParentId(iParent);
                        dictArea.setParentsIds(sParents);
                        dictArea.setAreaCode(eleAs.get(0).text());
                        dictAreaList.add(dictArea);
                        try {
                            dictAreaService.addData(dictAreaList);
                            dictAreaList.clear();
                            getTown(getUrl(sUrl) + eleAs.get(0).attr(sHref), Long.parseLong(getCode(eleAs.get(0).attr(sHref).replace(sReplace, ""))),
                                    sParents + "," + getCode(eleAs.get(0).attr(sHref).replace(sReplace, "")), dictAreaList);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
    }

    /**
     * 街道页面解析
     *
     * @param sUrl
     * @param iParent
     * @param sParents
     * @param dictAreaList
     */
    private void getTown(String sUrl, long iParent, String sParents, List<DictArea> dictAreaList) {
        String sResult = getString(HttpClientUtil.httpGetRequest(sUrl, "GB2312"));
        if (sResult.equals("")) return;
        Document document = Jsoup.parse(sResult);
        Elements elements = document.getElementsByAttributeValue("class", "towntable");
        if (elements != null && elements.size() > 0) {
            Element eleTable = elements.get(0);
            Elements eleTRs = eleTable.child(0).children().toggleClass("towntr");
            if (eleTRs != null && eleTRs.size() > 0) {
                for (Element eleTR : eleTRs
                        ) {
                    Elements eleAs = eleTR.getElementsByTag("a");
                    if (eleAs != null && eleAs.size() > 0) {
                        DictArea dictArea = new DictArea();
                        dictArea.setAreaName(eleAs.get(1).text());
                        dictArea.setId(Long.parseLong(getCode(eleAs.get(0).attr(sHref).replace(sReplace, ""))));
                        dictArea.setAreaType(3);
                        dictArea.setIsDelete(0);
                        dictArea.setCreateTime(new Date());
                        dictArea.setParentId(iParent);
                        dictArea.setParentsIds(sParents);
                        dictArea.setAreaCode(eleAs.get(0).text());
                        dictAreaList.add(dictArea);
                        try {
                            dictAreaService.addData(dictAreaList);
                            dictAreaList.clear();
                            getvillage(getUrl(sUrl) + eleAs.get(0).attr(sHref), Long.parseLong(getCode(eleAs.get(0).attr(sHref).replace(sReplace, ""))),
                                    sParents + "," + getCode(eleAs.get(0).attr(sHref).replace(sReplace, "")), dictAreaList);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
    }

    /**
     * 居委会页面解析
     *
     * @param sUrl
     * @param iParent
     * @param sParents
     * @param dictAreaList
     */
    private void getvillage(String sUrl, long iParent, String sParents, List<DictArea> dictAreaList) {
        String sResult = getString(HttpClientUtil.httpGetRequest(sUrl, "GB2312"));
        if (sResult.equals("")) return;
        Document document = Jsoup.parse(sResult);
        Elements elements = document.getElementsByAttributeValue("class", "villagetable");
        if (elements != null && elements.size() > 0) {
            Element eleTable = elements.get(0);
            Elements eleTRs = eleTable.child(0).children().toggleClass("villagetr");
            if (eleTRs != null && eleTRs.size() > 0) {

                for (int i = 1; i < eleTRs.size(); i++) {
                    Element eleTR = eleTRs.get(i);
                    Elements eleTDs = eleTR.getElementsByTag("td");
                    if (eleTDs != null && eleTDs.size() > 0) {
                        DictArea dictArea = new DictArea();
                        dictArea.setAreaName(eleTDs.get(2).text());
                        dictArea.setId(Long.parseLong(eleTDs.get(0).text()));
                        dictArea.setAreaType(4);
                        dictArea.setIsDelete(0);
                        dictArea.setCreateTime(new Date());
                        dictArea.setParentId(iParent);
                        dictArea.setParentsIds(sParents);
                        dictArea.setAreaCode(eleTDs.get(0).text());
                        dictAreaList.add(dictArea);
                    }
                }
                try {
                    dictAreaService.addData(dictAreaList);
                    dictAreaList.clear();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
